#!/bin/sh

# Normal users need sudo to install packages
[ $(id -u) != 0 ] && SUDO=sudo

source $LKP_SRC/lib/env.sh

load_distro_funcs()
{
	local distro="$1"

	test -e $LKP_SRC/distro/$distro && {
		source $LKP_SRC/distro/$distro
		return
	}

	test -e /etc/apt/sources.list && {
		source $LKP_SRC/distro/debian
		return
	}

	test -d /etc/yum.repos.d && {
		source $LKP_SRC/distro/centos
		return
	}

	echo "Your OS is not registered yet, please create $LKP_SRC/distro/$distro first"
	exit 1
}

# for packages with same dependencies, force the update instead of generating link
# due to schedule stage will auto detect symbolic link, so no need generate new link
check_shared_package()
{
	local bm_name="$1"

	[[ -L "$LKP_SRC/distro/depends/$bm_name" ]] || return

	local target
	target=$(readlink $LKP_SRC/distro/depends/$bm_name)
	target=$(basename $target)

	BM_NAME="$target"
}

show_deps_list()
{
	local denylist="^pack-deps$
-dev$
-allowlist$"

	find $LKP_SRC/distro/depends/ -type f | sed 's:.*/::' | grep -v "$denylist"
}

show_pack_list()
{
	local tmp_input="$(mktemp /tmp/lkp-tmpinput-XXXXXXXXX)"
	for i in monitors setup tests daemon
	do
		find $LKP_SRC/$i -type f -or -type l | sed 's:.*/::' >> $tmp_input
	done
	find  $LKP_SRC/pack -type f | sed 's:.*/::' |
	grep -x -F -f $tmp_input |
	grep -v -e '^0day-'
	rm $tmp_input &>/dev/null
}

install_runtime_depends()
{
	:
}

ospkg_update_ratelimit()
{
	local today=$(date +%F)
	local tsfile=/tmp/ospkg_update_ratelimit-$today

	test -f $tsfile && return
	touch $tsfile

	ospkg_update
}

ospkg_update_install()
{
	if [ -z "$1" ]; then
		echo "warning: empty package list in ospkg_update_install"
		return 0
	fi

	ospkg_update_ratelimit

	echo "Installing packages $*"
	ospkg_install "$*" ||
	ospkg_install "$*" ||
	ospkg_install "$@" || exit
}

update()
{
	:
}

fixup_distro_mirror()
{
	:
}

fixup_preinstall()
{
	:
}

fixup_arch_install()
{
	:
}

pack_benchmark_deps()
{
	:
}

add_i386_package()
{
	:
}

share_debian_package()
{
	[[ "$os" = "debian" ]] && return
	grep -qFx "$benchmark" $LKP_SRC/distro/share-debian || return

	date=$(date +"%Y%m%d")

	wget -q -P ${pack_to} http://${INITRD_HTTP_HOST}:8800/initrd/deps/${os_mount}/debian/${os_arch}/sid/${benchmark}/${benchmark}.cgz
	mv ${pack_to}/${benchmark}.cgz ${pack_to}/${benchmark}_${date}.cgz
	upload_to_target_dir ${pack_to}

	echo package uploaded to $pack_to/${benchmark}.cgz

	exit 0
}

upload_to_target_dir()
{
	. $LKP_SRC/lib/upload.sh

	local dir="$1"
	[ -d "${dir}" ] || return 0

	local file="$(ls -F ${dir} | grep -v "@")"
	[ -z "${file}" ] && return 0

	upload_one_curl "${dir}/${file}"  "${dir}" >/dev/null
}

rename_cgz_file()
{
	[ "${BM_NAME}" == "${benchmark}" ] && return

	cd "$pack_to" && {
		[ -f "${BM_NAME}".cgz ] || return
		rm "${BM_NAME}".cgz
		date=$(ls -F | grep -v "@" | grep -Eo "[0-9]{8}")
		mv "${BM_NAME}"_"$date".cgz "${benchmark}"_"$date".cgz
	}
}
